import { fileURLToPath, URL } from 'node:url'
import AutoImport from 'unplugin-auto-import/vite'
import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'
import Components from 'unplugin-vue-components/vite'
import { ElementPlusResolver } from 'unplugin-vue-components/resolvers'
import { createStyleImportPlugin, VxeTableResolve } from 'vite-plugin-style-import'
import { resolve } from 'path'
import { visualizer } from 'rollup-plugin-visualizer'
/** 路径查找 */
const pathResolve = (dir: string): string => {
  return resolve(__dirname, '.', dir)
}
// https://vitejs.dev/config/
export default defineConfig({
  plugins: [
    vue(),
    AutoImport({
      resolvers: [ElementPlusResolver()]
    }),
    Components({
      resolvers: [ElementPlusResolver()],
      directoryAsNamespace: true
    }),
    createStyleImportPlugin({
      resolves: [VxeTableResolve()]
    }),
    visualizer({
      gzipSize: true,
      brotliSize: true,
      emitFile: false,
      filename: 'test.html', //分析图生成的文件名
      open: true //如果存在本地服务端口，将在打包后自动展示
    })
  ],
  resolve: {
    alias: {
      '@': fileURLToPath(new URL('./src', import.meta.url))
    }
  },
  build: {
    sourcemap: false,
    // 消除打包大小超过500kb警告
    chunkSizeWarningLimit: 4000,
    rollupOptions: {
      input: {
        index: pathResolve('index.html')
      },
      // 静态资源分类打包
      output: {
        manualChunks(id, { getModuleInfo }) {
          if (id.includes('node_modules')) {
            // console.log(id.toString().split('node_modules/')[1].split('/')[1]);
            return id.toString().split('node_modules/')[1].split('/')[1].toString()
          }
          const reg = /(.*)\/src\/utils\/(.*)/
          if (reg.test(id)) {
            const importersLen = getModuleInfo(id)?.importers.length
            // 被多处引用
            if (importersLen && importersLen > 1) return 'common'
          }
        },
        chunkFileNames: 'static/js/[name]-[hash].js',
        entryFileNames: 'static/js/[name]-[hash].js',
        assetFileNames: 'static/[ext]/[name]-[hash].[ext]'
      }
    }
  },
  // 服务端渲染
  server: {
    // 端口号
    port: 5173,
    host: '0.0.0.0',
    proxy: {
      '^/api': {
        // 这里填写后端地址
        target: 'http://192.168.2.57:3001/api',
        changeOrigin: true,
        rewrite: (path) => path.replace(/^\/api/, '')
      }
    }
  }
})
